﻿

using System;
using System.Collections.Generic;
using System.Linq;
using WHLRDF.ORM;
using WHLRDF.ORG.Model;
using WHLRDF.Application.Model;
using WHLRDF.Application.BLL;

namespace WHLRDF.ORG.BLL
{
    public class DepartmentService : SerivceBase, IDepartmentService
    {
        #region 
        /// <summary>
        /// 部门
        /// </summary>
        public const string Department_Identity_Num = "0008";
        #endregion
        #region 基本方法
        /// <summary>
        /// 查询所有
        /// </summary>
        public List<DepartmentEntity> GetAll()
        {
            ICriterion criter = Expression.Eq(DepartmentEntity.__IsDeleted, false);
            return DbRepository.Query<DepartmentEntity>(criter).ToList();

        }
        /// <summary>
        /// 获取单个实例的方法
        /// <param name="id">object类型</param>
        /// </summary>
        public DepartmentEntity GetById(string id)
        {
            return DbRepository.GetById<DepartmentEntity>(id);

        }

       
        /// <summary>
        /// 删除方法
        /// <param name="deleteKey">主键，如果字符串请将字符串列表用单引号将字符串用上,如（'aaa','bbb'）</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Delete(string deleteKey, ref string strError)
        {
            if (!string.IsNullOrEmpty(deleteKey))
            {
                return DbRepository.Delete<DepartmentEntity>(deleteKey);
            }
            return true;
        }
        /// <summary>
        /// 分页查询方法
        /// <param name="grid">分页查询的相关参数</param>
        /// </summary>
        public LigerGrid ForGrid(LigerGrid grid)
        {
            ICriterion criter = Expression.Eq("IsDeleted", false);
            if (!string.IsNullOrEmpty(grid.keyWord))
            {
                criter = Expression.And(criter,

                           Expression.Like(new string[] {
                                DepartmentEntity._PrimaryKeyName ,
                           }, grid.keyWord)
                           );
            }
            return DbRepository.Query<DepartmentEntity>(grid, criter);

        }
        #endregion

        #region 扩展方法
        /// <summary>
        /// 通过组织架构编号获取下级部门
        /// </summary>
        /// <param name="parentId">上级部门Id</param>
        /// <param name="orgId">组织架构Id</param>
        /// <returns></returns>
        public List<DepartmentEntity> GetDeptByOrgId(string parentId, string orgId)
        {
            ICriterion criter = Expression.Eq(DepartmentEntity.__IsDeleted, false);
            if (string.IsNullOrWhiteSpace(parentId))
            {
                criter = Expression.And(criter, Expression.And(Expression.Eq(DepartmentEntity.__OrgId, orgId),
              Expression.Or(Expression.Eq(DepartmentEntity.__ParentId, ""), Expression.IsNull(DepartmentEntity.__ParentId))));
            }
            else
            {
                criter = Expression.And(criter,Expression.Eq(DepartmentEntity.__ParentId, parentId));
            }
            var lstEntity = DbRepository.Query<DepartmentEntity>(criter, new Order(DepartmentEntity.__OrderNum, true)).ToList();

            var lstTempEntity = new OrgChartService().GetTempChartEntities();
            if (lstTempEntity != null && lstTempEntity.Count > 0)
            {
                var resultTemp = lstTempEntity.Where(x => x.Department.OrgId.Equals(orgId) 
                && ((x.Department.ParentId.IsNullOrEmpty() 
                && string.IsNullOrWhiteSpace(parentId)) || (x.Department.ParentId == parentId))).ToList();
                if (resultTemp != null && resultTemp.Count > 0)
                {
                    foreach (var item in resultTemp)
                    {
                       var itemEntity=  lstEntity.Where(x => x.DepartmentId == item.Department.DepartmentId).FirstOrDefault();
                        if (itemEntity != null)
                        {
                            itemEntity = item.Department;
                        }
                        else
                        {
                            lstEntity.Add(item.Department);
                        }
                        //if (!item.Department.IsNewAdd)
                        //{
                        //   // lstEntity.RemoveAll(x => x.DepartmentId == item.Department.DepartmentId);
                        //}
                    }
                }
               // lstEntity = lstEntity.Union(resultTemp).ToList();
            }
            if ( lstEntity.Count>0)
            {
                lstEntity.ForEach(item => {
                    item.parent = string.IsNullOrWhiteSpace(item.ParentId) ? orgId:item.ParentId;
                    item.IsEdited = false;
                    if (item.IsCheckOut)
                    {
                        item.IsEdited = item.CheckOutUserId.Equals(ApplicationEnvironments.DefaultSession.UserId);
                        item.icon = item.IsEdited ? "fa fa-user" : "fa fa-lock";
                    }
                    item.LstChildren = DbRepository.Query<DepartmentEntity>(Expression.And(Expression.Eq(DepartmentEntity.__IsDeleted, false),
              Expression.Eq(DepartmentEntity.__ParentId, item.DepartmentId))).ToList();
                    item.children = item.LstChildren != null && item.LstChildren.Count > 0;
                });
            }
            return lstEntity.OrderBy(x=>x.OrderNum).ToList();
        }
        /// <summary>
        /// 判断名称是否存在
        /// </summary>
        /// <param name="deptName"></param>
        /// <param name="deptId"></param>
        /// <param name="deptParentId"></param>
        /// <returns></returns>
        public bool Exist(string deptName, string deptId,string deptParentId)
        {
            deptId = (string.IsNullOrWhiteSpace(deptId)) ? "" : deptId;
            deptParentId = (string.IsNullOrWhiteSpace(deptParentId)) ? "" : deptParentId;
            ICriterion criter = Expression.Eq("IsDeleted", false);
            criter = 
                Expression.And(criter, Expression.And(Expression.Eq(DepartmentEntity.__DepartmentName, deptName),
                 Expression.And( Expression.Eq(DepartmentEntity.__ParentId, deptParentId),
                Expression.NotEq(DepartmentEntity._PrimaryKeyName, deptId)))
                );
            var result = DbRepository.Query<DepartmentEntity>(criter).FirstOrDefault();
            return result != null;
        }

        /// <summary>
        /// 判断缩写是否存在
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        private bool IsExistCode(DepartmentEntity entity)
        {
            if (!string.IsNullOrWhiteSpace(entity.DepartmentCode))
            {
                var result = DbRepository.Query<DepartmentEntity>(Expression.And(Expression.Eq(DepartmentEntity.__IsDeleted, false),
                      Expression.And(Expression.NotEq(DepartmentEntity._PrimaryKeyName, entity.DepartmentId),

                      Expression.Eq(DepartmentEntity.__DepartmentCode, entity.DepartmentCode)))).FirstOrDefault();
                return result != null;
            }
            return false;
        }

        /// <summary>
        /// 保存方法
        /// <param name="entity">对象</param>
        /// <param name="strError">错误信息</param>
        /// <param name="isSave">是否物理保存</param>
        /// </summary>
        public bool Save(DepartmentEntity entity, ref string strError, bool isSave = true)
        {
            entity.DepartmentId = string.IsNullOrWhiteSpace(entity.DepartmentId) ? "" : entity.DepartmentId;
            if (ExistDept(entity, ref strError))
            {
                return false;
            }
            DepartmentEntity parentEntity = string.IsNullOrEmpty(entity.ParentId) ? null : this.GetById(entity.ParentId);
            if (string.IsNullOrWhiteSpace(entity.DepartmentId))
            {
                Dictionary<string, string> dicParam = new Dictionary<string, string>();
                //dicParam.Add("ORGID", entity.OrgId);
                entity.DepartmentId = SerialService.CreateSerialNo(Department_Identity_Num, dicParam, ref strError);
                entity.IsCheckOut = true;
                entity.CheckOutUserId = ApplicationEnvironments.DefaultSession.UserId;
                entity.CheckOutIp = ApplicationEnvironments.DefaultSession.IPAddress;
                entity.icon = "fa fa-user";
                entity.IsNewAdd = true;
            }
            if (!entity.IsCheckOut || !entity.CheckOutUserId.Equals(ApplicationEnvironments.DefaultSession.UserId))
            {
                strError = "该部门尚未迁出或者已经被其它用户迁出，您无法进行操作！";
                return false;
            }
            entity.ParentId = string.IsNullOrEmpty(entity.ParentId) ? "" : entity.ParentId;
           // entity.DepartmentPath = (parentEntity != null) ? (parentEntity.DepartmentPath + "_" + parentEntity.DepartmentId.ToString()) : "";
            if (!isSave)
            {
                return true;
            }
            //  var actionService = new PageActionService();
            using (var tran = DbRepository.Begin())
            {
                try
                {
                    DbRepository.SaveOrUpdate<DepartmentEntity>(entity);

                    DbRepository.Commit();
                }
                catch (Exception ex)
                {

                    DbRepository.Rollback();
                    throw ex;
                }

            }

            return OnSavedEventHandler(entity, ref strError);

        }

        /// <summary>
        /// 判断部门名称 部门缩写是否存在
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool ExistDept(DepartmentEntity entity, ref string strError)
        {
            if (this.IsExistCode(entity))
            {
                strError = "【" + entity.DepartmentCode + "】" + "已存在";
                return true;
            }
            if (this.Exist(entity.DepartmentName,entity.DepartmentId,entity.ParentId))
            {
                strError = "【" + entity.DepartmentName + "】" + "已存在";
                return true;
            }
            return false;
        }

        /// <summary>
        /// 删除方法
        /// <param name="deleteKey">主键</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool SingleDelete(string deptid, ref string strError)
        {
            if (!string.IsNullOrEmpty(deptid))
            {
               
                var entity = this.GetById(deptid);
                if (entity == null)
                {
                    new OrgChartService().TempDeptDelete(deptid);
                }
                if (!entity.IsCheckOut|| !entity.CheckOutUserId.Equals(ApplicationEnvironments.DefaultSession.UserId))
                {
                    strError = "部门未迁出或者不是本人迁出，无法删除！";
                    return false;
                }
                var children = this.Query<DepartmentEntity>(Expression.And(Expression.Eq(DepartmentEntity.__IsDeleted, false),
                  Expression.Eq(DepartmentEntity.__ParentId, entity.DepartmentId))).ToList();
                if (children != null && children.Count > 0)
                {
                    strError = "该部门下还存在其他部门，请先将下级部门关系移除后在删除！";
                    return false;
                }
                using (var tran = this.Begin())
                {
                    try
                    {
                        this.Delete<JobFunctionEntity>(Expression.And(Expression.Eq(JobFunctionEntity.__IsDeleted, false),
                  Expression.Eq(JobFunctionEntity.__DepartmentId, entity.DepartmentId)),false);
                        this.Delete<RelationUserEntity>(Expression.And(Expression.Eq(RelationUserEntity.__RelationType, RelationUserType.Dept.GetHashCode()),
                Expression.Eq(RelationUserEntity.__ResourceId, entity.DepartmentId)), false);
                        this.Delete(entity);
                        this.Commit();
                    }
                    catch (Exception ex)
                    {
                        this.Rollback();
                        throw ex;
                    }
                }
                new OrgChartService().TempDeptDelete(deptid);

            }
            return true;
        }

        /// <summary>
        /// 获取部门
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public List<DepartmentEntity> GetDepartmentByName(string keyword,string orgId)
        {
            ICriterion criter = Expression.Eq(DepartmentEntity.__IsDeleted, false);
           
            if (string.IsNullOrWhiteSpace(keyword))
            {
                keyword = "";
                criter = Expression.And(criter, Expression.And(Expression.Eq(DepartmentEntity.__OrgId, orgId),
              Expression.Or(Expression.Eq(DepartmentEntity.__ParentId, ""), Expression.IsNull(DepartmentEntity.__ParentId))));
            }
            if (!string.IsNullOrWhiteSpace(keyword))
            {
                criter = Expression.And(criter, Expression.Like(new string[] {
                DepartmentEntity.__DepartmentName,
                DepartmentEntity.__DepartmentCode,
                DepartmentEntity._PrimaryKeyName
             }, keyword));
            }
            var lstEntity = DbRepository.Query<DepartmentEntity>(criter, new Order(DepartmentEntity.__OrderNum, true)).ToList();
            var lstTempEntity = new OrgChartService().GetTempChartEntities();
            if (lstTempEntity != null && lstTempEntity.Count > 0)
            {
                var resultTemp = lstTempEntity.Where(x => x.Department.OrgId.Equals(orgId)&&x.Department.DepartmentName.Contains(keyword)).ToList();
                if (resultTemp != null && resultTemp.Count > 0)
                {
                    foreach (var item in resultTemp)
                    {
                       var itemEntity=  lstEntity.Where(x => x.DepartmentId == item.Department.DepartmentId).FirstOrDefault();
                        if (itemEntity == null)
                        {
                            lstEntity.Add(item.Department);
                        }
                        else
                        {
                            itemEntity = item.Department;
                        }
                    }
                }
              
            }

            return lstEntity;
        }
        #endregion

        #region Event

        /// <summary>
        /// 保存成功事件
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        private bool OnSavedEventHandler(DepartmentEntity entity, ref string strError)
        {
            return true;
        }

        /// <summary>
        /// 删除后执行的事件
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        private bool OnDeletedEventHandler(DepartmentEntity entity)
        {
            return true;
        }
        #endregion 

    }
}